<?php


namespace App\Http\Controllers\App;


use App\Exceptions\FailException;
use App\Http\Controllers\Controller;
use App\Http\Services\MemberServices;
use App\Models\Feedback;
use App\Models\InviteCode;
use App\Models\MemberCollectionStore as MemberCollectionStoreAlias;
use App\Models\Member;
use App\Models\MemberCollectionStore;
use App\Models\MemberOrder;
use App\Models\SmsMsg;
use App\Models\Store;
use App\Models\StoreComment;
use Carbon\Carbon;
use DB;
use Exception;
use Illuminate\Http\Request;
use Auth;
use Log;

class MemberController extends Controller
{
    public function favorite()
    {
        $user = Auth::user();
        $time = request('time');
        $model = MemberCollectionStoreAlias::whereMemberId($user->id);
        if ($time == 'yd') {
            $model->whereDate(MemberCollectionStoreAlias::TABLE . '.created_at', Carbon::yesterday());
        }elseif ($time == '7') {
            $model->whereDate(MemberCollectionStoreAlias::TABLE . '.created_at', '>', Carbon::today()->subDay(7));
        }elseif ($time == 'month') {
            $model->whereDate(MemberCollectionStoreAlias::TABLE . '.created_at', '>', Carbon::today()->subDay(30));
        }else{

        }
        $lon = \request('lon', 0);
        $let = \request('let', 0);
        $list = $model->leftJoin(Store::TABLE, Store::TABLE . '.id', '=', MemberCollectionStoreAlias::TABLE . '.store_id')
            ->select([
                MemberCollectionStoreAlias::TABLE . '.id',
                MemberCollectionStoreAlias::TABLE . '.created_at',
                DB::raw(Store::distance($lon, $let)),
                'name',
                'background',
                'score',
                'area'
            ])->get();
        return $list;
    }

    public function favoriteStore()
    {
        $this->validate(\request(), [
            'store_id' => 'required'
        ], [
            'store_id.required' => '店铺id不能为空'
        ]);
        $store = Store::find(\request('store_id'));
        if (!$store) {
            throw new FailException('店铺不存在');
        }
        if (MemberCollectionStoreAlias::where('member_id', Auth::id())->where('store_id', \request('store_id'))->first()) {
            throw new FailException('你已经收藏过了');
        }
        try {
            DB::beginTransaction();
            $mcs = new MemberCollectionStoreAlias();
            $mcs->member_id = Auth::id();
            $mcs->store_id = \request('store_id');
            $mcs->created_at = Carbon::now();
            if (!$mcs->save()) {
                throw new FailException('收藏失败');
            }
            $store->increment('collects');
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            Log::error($e);
        }

        return success('收藏成功');
    }

    public function unFavorite()
    {
        $this->validate(\request(), [
            'id' => 'required'
        ]);
        if (!MemberCollectionStoreAlias::find(\request('id'))) {
            throw new FailException('找不到数据');
        }
        MemberCollectionStoreAlias::destroy(\request('id'));
        if ($store = Store::find(\request('id'))){
            $store->decrement('collects');
        }
        return success('取消收藏成功');
    }
    /**
     * 保存信息
     * @param Request $request
     * @return array
     * @throws FailException
     */
    public function save(Request $request)
    {
        $this->validate($request,[
            'name' => 'required',
            'avatar' => 'required',
        ],[
            'name.required' => '姓名不能为空！',
            'avatar.required' => '头像不能为空！'
        ]);
        $member = Auth::user();
        $member->name = $request->input("name");
        $member->avatar = $request->input("avatar");
        $member->autograph = $request->input("autograph");
        try{
            DB::beginTransaction();
            $member->save();
            DB::commit();
            return [];

        }catch (Exception $exception){
            Log::error($exception);
            DB::rollBack();
            throw new FailException("保存失败");
        }

    }

    // todo 找回密码
    //region 修改密码
    /**
     * 修改密码
     * @param Request $request
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */
    public function retrievePassword ( Request $request, SmsMsg $msg )
    {
        $this->validate ( $request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
            'password' => 'required|string|min:6|max:20'
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',
            'password.required' => 'password不能为空',
            'password.min' => 'password不小于:min位',
            'password.max' => 'password不大于:max位',
        ] );
        $phone = $request->input("phone");

        $code = $request->input("code");
        $password = bcrypt($request->input('password' ) );
        // 验证短信
        $msg->validate ( $phone, $code );
        $user = Member::where ( "phone", $phone )->first();
        if (isset( $user )) {
            $user->password = $password;
            $user->save ();
            $token = Auth::guard ( 'app' )->fromUser ( $user );
            return $this->renderJson ( ['token' => $token, 'expire' => '2592000'] );
        }
        return $this->fail ( "账号不存在，请注册！" );
    }

    //region todo 更换手机号码
    public function modifyPhone(Request $request, SmsMsg $msg)
    {
        $this->validate ( $request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',

        ] );
        $phone = $request->input('phone');
        $code = $request->input('code');
        $msg->validate($phone,$code);
        if (Member::wherePhone($phone)->first()){
            throw new FailException("改手机已注册！");
        }
        $member = Member::whereId(Auth::id())->first();
        $member->phone = $phone;
         $save = $member->save();
         if (!$save){
             throw new FailException("修改失败！");
         }
         return $this->success('修改成功！');
    }
    //endregion

    //region todo 获取会员邀请码
    public function getInviteCode()
    {
        $code = mt_rand(10000000,99999999);

        $invite_code = InviteCode::firstOrCreate(["target_id" => Auth::id(), "target_type" => 0],[
            "target_id" => Auth::id(),
            "code" => $code
        ]);


        return $this->renderJson(["code"=>$invite_code->code]);
    }

    //endregion

    public function wallet()
    {
        $memberService = new MemberServices();
        $balance = $memberService->getBalance();
        $num = $memberService->getNum();
        $rank = $memberService->bonusRank();
        $award = $memberService->award();
        return array_merge($balance, $num, $rank, $award);
    }

    public function walletOrderList()
    {
        $memberService = new MemberServices();
        return $memberService->getLatelyOrder();
    }


    // todo 会员基础信息
    public function info()
    {
        $id = Auth::id();
        // 会员信息
        $member = Member::whereId($id)->first();
        //收藏店铺
        $favorites_store_num = MemberCollectionStore::whereMemberId($id)->count();
        // 订单个数
        $member_order_num = MemberOrder::whereMemberId($id)->count();
        // 反馈个数
        $feedback_num = Feedback::whereMemberId($id)->count();

        return $this->renderJson([
            'id' => $member->id,
            'name' => $member->name,
            'phone' => $member->phone,
            'avatar' => $member->avatar,
            'useable_bonus_money' => $member->useable_bonus_money,
            'total_bonus_money' => $member->total_bonus_money,
            'card_money' => $member->card_money,
            'card_money_coupon' => $member->card_money_coupon,
            'total_share_money' => $member->total_share_money,
            'useable_share_money' => $member->useable_share_money,
            'created_at' => $member->created_at->format("Y-m-d H:i:s"),
            'favorites_store_num' => $favorites_store_num,
            'order_num' => $member_order_num,
            'feedback_num' => $feedback_num,
            'gender' => $member->gender,
            'birthday' => $member->birthday
        ]);


    }

    public function comment()
    {
        $lon = \request('lon', 0);
        $let = \request('let', 0);
        $time = \request('time');
        $model = StoreComment::select('store_comment.id','s.name','s.logo', 's.score', 's.area','store_comment.store_id', DB::raw(Store::distance($lon, $let)))
            ->leftJoin('store as s', 's.id', '=', 'store_comment.store_id');
        if ($time == 'yd') {
            $model->whereDate('store_comment.created_at', Carbon::yesterday());
        } elseif ($time == '7') {
            $model->whereDate('store_comment.created_at', '>', Carbon::today()->subDay(7));
        } elseif ($time == 'month') {
            $model->whereDate('store_comment.created_at', '>', Carbon::today()->subDay(30));
        } else {
            $model->whereDate('store_comment.created_at', '=', Carbon::today());
        }
        return $model->paginate();
    }

    public function update()
    {
        $member = Member::find(Auth::id());
        if (\request()->has('name')) {
            $member->name = \request('name');
        }
        if (\request()->has('avatar')) {
            $member->name = \request('name');
        }
        if (\request()->has('gender')) {
            $member->name = \request('gender');
        }
        if (\request()->has('birthday')) {
            $member->name = \request('birthday');
        }
        $member->save();
        return success('修改成功');
    }
}